import { defineStore } from 'pinia';
import { nextTick, ref } from 'vue';
import { APP_CONFIG } from '@/jiessConfig/consts';
import tokenCookie from '@/assets/utils/cookies/token';
const { routeHome, everyModeUser } = APP_CONFIG;
// defineStore 调用后返回一个函数，调用该函数获得 Store 实体
export const useStore = defineStore({
	// id: 必须的，在所有 Store 中唯一
	id: 'globalState',
	state: () => ({
		routeInfo: {
			from: {},
			to: {
				meta: {
					useLoading: true
				}
			}
		},
		// 在跳转已被缓存的页面时，
		// 标签和菜单切换应当保留缓存，
		// 普通跳转遇到相同页面不保留缓存
		routeCleanCache: true,
		cacheRoutes: [],
		currentTabVal: routeHome.name,
		isCollapse: ref(false),
		currentTab: routeHome,
		tabItems: [routeHome],
		refreshState: true,
		accountInfo: {},
		menus: []
	}),
	actions: {
		setMenus(data) {
			return (this.menus = data);
		},
		setAccountInfo(data) {
			return (this.accountInfo = data);
		},
		setTabItems(data) {
			return (this.tabItems = data);
		},
		setCurrentTab(data) {
			if (data.name === this.currentTab.name) {
				return;
			}
			if (!this.tabItems.find(item => item.name === data.name)) {
				this.tabItems.push(data);
			}
			this.currentTab = data;
			this.currentTabVal = data.name;
		},
		setRouteCleanCache(data) {
			this.routeCleanCache = data;
		},
		setRouteInfo(data) {
			this.routeInfo = data;
		},
		async cleanToRouteCache(name) {
			if (this.tabItems.find(item => item.name === name)) {
				await this.cleanCache(name);
			}
		},
		addRouteCache(to) {
			const { useCache, name } = to.meta || {};
			if (useCache && !this.cacheRoutes.includes(name)) {
				this.cacheRoutes.push(name);
			}
		},
		async cleanCache(name) {
			const { cacheRoutes } = this;
			const idx = cacheRoutes.findIndex(val => val === name);
			cacheRoutes.splice(idx, 1);
			await new Promise(resolve => {
				nextTick(() => resolve(cacheRoutes.push(name)));
			});
		},
		refresh(name = this.currentTab.name) {
			this.cleanCache(name);
			this.refreshState = false;
			nextTick(() => (this.refreshState = true));
		},
		async getAccountInfo() {
			try {
				let data = null;
				if (import.meta.env.VITE_ACCESS_MODE === 'every') {
					data = everyModeUser;
				} else {
					data = JSON.parse(localStorage.userData)
				}
				return this.setAccountInfo(data);
			} catch (e) {
				// return Promise.reject('账户信息获取失败');
				return Promise.reject(e);
			}
		},
		removeTab(name) {
			const index = this.tabItems.findIndex(item => item.name === name);
			if (index > -1) {
				setTimeout(() => this.cleanCache(name));
				this.tabItems.splice(index, 1);
				if (name === this.currentTab.name) {
					this.setCurrentTab(this.tabItems[index - 1]);
				}
			}
		},
		logout() {
			tokenCookie.remove();
			window.location.reload();
		},
		toggleCollapse() {
			this.isCollapse = !this.isCollapse;
		}
	}
});